package com.lujieni.springbootmybatis.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lujieni.springbootmybatis.aop.TenantIgnore;
import com.lujieni.springbootmybatis.context.TenantContextHolder;
import com.lujieni.springbootmybatis.po.PersonDO;
import com.lujieni.springbootmybatis.service.IPersonService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author：Jie Ni
 * @Date: 2025/6/16 9:16
 * @Description:
 */
@RestController
@RequestMapping("/person")
@RequiredArgsConstructor
public class PersonController {

    private final IPersonService personService;

    @GetMapping("/getByIdWithinTenant/{id}")
    public PersonDO getByIdWithinTenant(@PathVariable Long id){
        return personService.getById(id);
    }

    @GetMapping("/getByIdWithoutTenant/{id}")
    @TenantIgnore
    public PersonDO getByIdWithoutTenant(@PathVariable Long id){
        return personService.getById(id);
    }


    @GetMapping("/getPage")
    public Page<PersonDO> getPage(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "2") int size, HttpServletRequest request){
        // 从请求头或token中获取租户ID
        String tenantId = request.getHeader("tenant_id");
        TenantContextHolder.setTenantId(Long.parseLong(tenantId));
        try {
            return personService.getPage(current, size);
        } finally {
            TenantContextHolder.clear();
        }
    }

    @GetMapping("/getPageByAge")
    public IPage<PersonDO> getPageByAge(String age, @RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "2") int size, HttpServletRequest request){
        // 从请求头或token中获取租户ID
        String tenantId = request.getHeader("tenant_id");
        TenantContextHolder.setTenantId(Long.parseLong(tenantId));
        Page<PersonDO> page = new Page<>(current, size);
        try {
            return personService.selectByAge(page, age);
        } finally {
            TenantContextHolder.clear();
        }
    }

    @PostMapping("/insert")
    public void insert(@RequestBody PersonDO person, HttpServletRequest request){
        // 从请求头或token中获取租户ID
        String tenantId = request.getHeader("tenant_id");
        TenantContextHolder.setTenantId(Long.parseLong(tenantId));
        try {
             personService.insert(person);
        } finally {
            TenantContextHolder.clear();
        }
    }

}
